import { LOGIN_TOKEN } from '@/global/constants'
import { localCache } from '@/utils/storage'
import { createRouter, createWebHashHistory } from 'vue-router'
import { firstMenu } from '@/utils/map-menus'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/main' // 设置访问根路径重定向
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/Login.vue')
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/Main.vue')
    },
    {
      path: '/:pathMatch(.*)',
      name: 'notFount',
      component: () => import('../views/not-found/NotFount.vue')
    }
  ]
})

// 全局路由守卫
router.beforeEach((to) => {
  const token = localCache.getStorage(LOGIN_TOKEN)

  if (to.path === '/main' && !token) {
    return '/login'
  } else if (to.path === '/main') {
    // 如果是进入到/main，且有token的情况下（上一个if已经判断没有token了）
    return firstMenu?.url
  }
})

export default router
